import { makeAutoObservable } from "mobx";
import Taro from "@tarojs/taro";
import {
  initLzbluetooth,
  startScanning,
  bindDevice,
  setMonitorDevice,
  DeviceInfo
} from "../../BPDevice-weapp-sdk";
// const lzbluetooth = Taro.requirePlugin("lzbluetooth");

export class IndexStore {
  /** 重试绑定次数 */
  tryBindcount = 3;
  scanDeviceMap = new Map<string, DeviceInfo>();
  constructor() {
    makeAutoObservable(this);
  }

  sdkInit() {
    Taro.openBluetoothAdapter({
      success: () => {
        initLzbluetooth();
        // this.MonitorDevice();
        this.searchDevice();
      }
    });
  }

  get scanDeviceList() {
    return Array.from(this.scanDeviceMap.values());
  }

  /** 扫描设备 */
  searchDevice() {
    startScanning((res: DeviceInfo) => {
      if (!res.mac) return;
      this.scanDeviceMap.set(res.mac, res);
    });
  }

  /** 直接添加已经绑定过的设备 */
  MonitorDevice() {
    setMonitorDevice([{ mac: "000814000A8F", model: "LS818-B" }]);
  }

  getbindDevice(mac: string) {
    bindDevice({
      mac,
      callback: res => {
        console.log("请求绑定的回调", res);
        if (res.deviceInfo.connectStatus !== 4) {
          this.tryBindDevice(mac);
        }
      }
    });
    // Taro.createBLEConnection({
    //   deviceId: mac,
    //   success: (res) => {
    //     console.log('蓝牙连接回调', res);
    //   },
    // });
  }
  /** 重新绑定 */
  tryBindDevice(mac: string) {
    this.tryBindcount--;
    if (this.tryBindcount === 0) return;
    this.getbindDevice(mac);
  }
}
